#include "stdafx.h"
#include <cctype>
#include "crHttpUtils.h"

NS_CR_BEGIN

#define NOMINMAX
#undef max
#undef min

namespace http
{
	namespace utils
	{

		Header parseHeader(const string& headers)
		{
			Header header;
			_STD vector<string> lines;
			_STD istringstream stream(headers);

			{
				string line;
				while (_STD getline(stream, line, '\n'))
					lines.push_back(line);
			}

			for (auto& line: lines) 
			{
				if (line.substr(0, 5) == "HTTP/")
				{
					header.clear();
				}

				if (line.length() > 0)
				{
					auto found = line.find(":");
					if (found != string::npos)
					{
						auto value = line.substr(found + 1);
						value.erase(0, value.find_first_not_of("\t"));
						value.resize(_STD min(value.size(), value.find_last_not_of("\t\n\r") + 1));
						header[line.substr(0, found)] = value;
					}
				}
			}
		
			return header;
		}

		size_t writeFunction(void* ptr, size_t size, size_t nmemb, string* data)
		{
			data->append(static_cast<char*>(ptr), size* nmemb);
			return size * nmemb;
		}

		string urlEncode(const string& value)
		{
			_STD ostringstream escaped;
			escaped.fill('0');
			escaped << _STD hex;

			for (auto i = value.cbegin(), n = value.cend(); i != n; ++i)
			{
				string::value_type c = (*i);

				if ( _STD isalnum(c) || c == '-' || c== '_' || c == '.' || c == '~')
				{
					escaped << c;
					continue;
				}

				escaped << '%' << _STD setw(2) <<  int32_t(static_cast<unsigned char>(c));
			}

			return escaped.str();
		}

	}
}

NS_CR_END